import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button as AButton, Spin as ASpin, Card as ACard } from 'antd';
import { EditOutlined } from '@ant-design/icons';

import { getRulesContentApi, type RuleConfigContent } from '@/api/rulesWarningConfig';
import EditTriggerRulesDrawer from './EditTriggerRulesDrawer';
import EditActionRulesDrawer from './EditActionRulesDrawer';

/**
 * 规则编辑页面组件
 */
const RuleEditBox: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const ruleId = searchParams.get('ruleId');
  const alarmRuleInfoId = searchParams.get('id'); // 获取场景联动信息ID

  const [loading, setLoading] = useState(true);
  const [ruleContent, setRuleContent] = useState<RuleConfigContent | null>(null);
  const [triggerDrawerOpen, setTriggerDrawerOpen] = useState(false);
  const [actionDrawerOpen, setActionDrawerOpen] = useState(false);

  // 获取规则配置内容
  const fetchRuleContent = async () => {
    if (!ruleId || ruleId == 'null') {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      const res = await getRulesContentApi(ruleId);

      if (res.success && res.data) {
        setRuleContent(res.data);
        console.log('规则配置内容:', res.data);
      } else {
        window.$message.error(res.errorMsg || '获取规则配置失败');
        setRuleContent(null);
      }
    } catch (error) {
      console.error('获取规则配置失败:', error);
      window.$message.error('网络错误，获取规则配置失败');
      setRuleContent(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRuleContent();
  }, [ruleId]);

  // 渲染值的辅助函数
  const renderValue = (value: unknown): string => {
    if (value === null || value === undefined || value === '') {
      return '暂无数据';
    }
    return String(value);
  };

  // 获取匹配模式文本
  const getMatchModeText = (mode?: number) => {
    return mode === 1 ? '满足全部条件执行' : '满足任意条件执行';
  };

  // 获取执行模式文本
  const getExecutionModeText = (mode?: string) => {
    console.log('mode', mode);
    return mode === 'serial' ? '串行' : '并行';
  };

  // 获取动作类型文本
  const getActionTypeText = (actionType?: string) => {
    const actionTypeMap: Record<string, string> = {
      alarm: '告警中心',
      sms: '短信通知',
      email: '邮件通知',
      http: '第三方推送',
      cmddown: '指令下发',
    };
    return actionTypeMap[actionType || ''] || actionType || '未知';
  };

  // 获取动作详细信息
  const getActionDetailText = (action: unknown) => {
    const actionTypeName = getActionTypeText(action.actionTypeName);

    if (!action.param) {
      return <span className="font-medium text-gray-900">{actionTypeName}</span>;
    }

    let param: unknown;
    try {
      param = typeof action.param === 'string' ? JSON.parse(action.param) : action.param;
    } catch {
      param = action.param;
    }

    switch (action.actionTypeName) {
      case 'sms':
        return param.smsAddress ? (
          <span>
            <span className="font-medium text-gray-900">{actionTypeName}</span>
            <span className="text-gray-700 ml-2">{param.smsAddress.join(', ')}</span>
          </span>
        ) : (
          <span className="font-medium text-gray-900">{actionTypeName}</span>
        );
      case 'email':
        return param.emailAddress ? (
          <span>
            <span className="font-medium text-gray-900">{actionTypeName}</span>
            <span className="text-gray-700 ml-2">{param.emailAddress.join(', ')}</span>
          </span>
        ) : (
          <span className="font-medium text-gray-900">{actionTypeName}</span>
        );
      case 'http':
        return (
          <span>
            <span className="font-medium text-gray-900">{actionTypeName}</span>
            <span className="text-gray-700 ml-2">
              url: {param.url || ''}, header: {param.header || ''}, method: {param.method || ''}
            </span>
          </span>
        );
      case 'cmddown':
        return (
          <span>
            <span className="font-medium text-gray-900">{actionTypeName}</span>
            <span className="text-gray-700 ml-2 font-mono text-xs">
              {JSON.stringify({
                identifier: param.identifier || '',
                inputParam: param.inputParam || {},
                deviceCodes: param.deviceCodes || [],
                productCode: param.productCode || '',
                serviceName: param.serviceName || '',
              })}
            </span>
          </span>
        );
      default:
        return <span className="font-medium text-gray-900">{actionTypeName}</span>;
    }
  };

  // 处理编辑触发规则
  const handleEditTriggerRules = () => {
    setTriggerDrawerOpen(true);
  };

  // 处理编辑动作规则
  const handleEditActionRules = () => {
    setActionDrawerOpen(true);
  };

  // 处理编辑成功后的回调
  const handleEditSuccess = (newRuleId?: string) => {
    if (newRuleId && (!ruleId || ruleId === 'null')) {
      const newSearchParams = new URLSearchParams(searchParams);
      newSearchParams.set('ruleId', newRuleId);
      setSearchParams(newSearchParams, { replace: true });
    } else {
      fetchRuleContent(); // 重新获取数据
    }
  };

  if (loading) {
    return (
      <ACard className="mt-6">
        <div className="text-center py-12">
          <ASpin size="large" />
          <p className="mt-4 text-gray-500">加载规则配置中...</p>
        </div>
      </ACard>
    );
  }
  const displayRuleContent = ruleContent || {
    perfectMatchMode: 1,
    conditions: [],
    actionExecutionMode: 'parallel',
    actions: [],
    silencePeriod: 0,
  };
  const isShow = true;

  return (
    <ACard className="mt-6">
      {isShow && (
        <>
          {/* 规则内容标题 */}
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-medium text-gray-900">规则内容</h3>
            <AButton
              type="link"
              icon={<EditOutlined />}
              onClick={handleEditTriggerRules}
              className="text-blue-600 hover:text-blue-700"
            >
              编辑触发规则
            </AButton>
          </div>
          {/* 触发条件表格 */}
          <div
            className="rounded-lg mb-6 overflow-hidden bg-white shadow-sm"
            style={{ border: '1px solid #d1d5db' }}
          >
            {/* 触发条件标题行 */}
            <div className="bg-gray-50" style={{ borderBottom: '1px solid #d1d5db' }}>
              <div className="flex">
                <div
                  className="w-32 px-4 py-3 flex items-center"
                  style={{ borderRight: '1px solid #d1d5db' }}
                >
                  <span className="font-medium text-gray-700">触发条件</span>
                </div>
                <div className="flex-1 px-4 py-3 flex items-center justify-end">
                  <span className="text-sm text-gray-500">
                    限制：{getMatchModeText(displayRuleContent.perfectMatchMode)}
                  </span>
                </div>
              </div>
            </div>

            {/* 条件列表 */}
            {displayRuleContent.conditions && displayRuleContent.conditions.length > 0 ? (
              displayRuleContent.conditions.map((condition, index) => (
                <div
                  key={condition.id || index}
                  style={{
                    borderBottom:
                      index < displayRuleContent.conditions!.length - 1
                        ? '1px solid #d1d5db'
                        : 'none',
                  }}
                >
                  <div className="flex">
                    <div
                      className="w-32 px-4 py-3 bg-gray-50 flex items-center"
                      style={{ borderRight: '1px solid #d1d5db' }}
                    >
                      <span className="text-sm font-medium text-gray-700">条件{index + 1}</span>
                    </div>
                    <div className="flex-1 px-4 py-3 flex items-center bg-white">
                      <span className="text-sm text-gray-900">
                        {renderValue(condition.conditionContent)}
                      </span>
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="px-4 py-8 text-center text-gray-500 bg-white">
                <p>暂无触发条件配置</p>
              </div>
            )}
          </div>
        </>
      )}

      {/* 编辑动作规则按钮 */}

      {/* 动作表格 */}
      {ruleId && ruleId != 'null' && (
        <>
          <div className="flex justify-end mb-4">
            <AButton
              type="link"
              icon={<EditOutlined />}
              onClick={handleEditActionRules}
              className="text-blue-600 hover:text-blue-700"
            >
              编辑动作规则
            </AButton>
          </div>
          <div
            className="rounded-lg overflow-hidden bg-white shadow-sm"
            style={{ border: '1px solid #d1d5db' }}
          >
            {/* 动作标题行 */}
            <div className="bg-gray-50" style={{ borderBottom: '1px solid #d1d5db' }}>
              <div className="flex">
                <div
                  className="w-32 px-4 py-3 flex items-center"
                  style={{ borderRight: '1px solid #d1d5db' }}
                >
                  <span className="font-medium text-gray-700">动作</span>
                </div>
                <div className="flex-1 px-4 py-3 flex items-center justify-end">
                  {/* <span className="text-sm text-gray-500">
                  执行方式：{getExecutionModeText(displayRuleContent.actionExecutionMode)}
                </span> */}
                </div>
              </div>
            </div>

            {/* 动作列表 */}
            {displayRuleContent.actions && displayRuleContent.actions.length > 0 ? (
              displayRuleContent.actions.map((action, index) => (
                <div
                  key={index}
                  style={{
                    borderBottom:
                      index < displayRuleContent.actions!.length - 1 ? '1px solid #d1d5db' : 'none',
                  }}
                >
                  <div className="flex">
                    <div
                      className="w-32 px-4 py-3 bg-gray-50 flex items-center"
                      style={{ borderRight: '1px solid #d1d5db' }}
                    >
                      <span className="text-sm font-medium text-gray-700">动作{index + 1}</span>
                    </div>
                    <div className="flex-1 px-4 py-3 flex items-center bg-white">
                      <div className="text-sm break-all">{getActionDetailText(action)}</div>
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="px-4 py-8 text-center text-gray-500 bg-white">
                <p>暂无动作配置</p>
              </div>
            )}
          </div>
        </>
      )}

      {/* 编辑触发规则抽屉 */}
      <EditTriggerRulesDrawer
        open={triggerDrawerOpen}
        onClose={() => setTriggerDrawerOpen(false)}
        ruleId={ruleId}
        alarmRuleInfoId={alarmRuleInfoId}
        initialData={displayRuleContent}
        onSuccess={handleEditSuccess}
      />

      {/* 编辑动作规则抽屉 */}
      <EditActionRulesDrawer
        open={actionDrawerOpen}
        onClose={() => setActionDrawerOpen(false)}
        ruleId={ruleId}
        initialData={displayRuleContent}
        onSuccess={handleEditSuccess}
      />
    </ACard>
  );
};

export default RuleEditBox;
